from flask import session,request
from functools import wraps
from DAL.sqlHelper import (get_adm_conn as conn_a,SQL_ADD_FIELD_VALUES)

def add(name='', content='', sql_record=''):
    param = locals()
    try:
        param['name'] = param['name'].replace("'", "''")
        param['content'] = param['content'].replace("'", "''")
        param['sql_record'] = param['sql_record'].replace("'", "''")
        sql_field, sql_values = SQL_ADD_FIELD_VALUES(param)
        sql = """
               INSERT INTO  `adm_log`({0},create_time)
               VALUES({1},NOW())
               """
        sql = sql.format(sql_field, sql_values)
        with conn_a() as conn:
            with conn.cursor() as cursor:
                cursor.execute(sql)
                conn.commit()
                res = cursor.rowcount
                return res
    except:
        return 0
    pass
def log(api_url=""):
    def warpper_fun(fn):
        @wraps(fn)
        def logToSQL(*args,**kwargs):
            account = session.get("account") or "未知"
            param = str(list(request.form.items()) )
            add(name=account,content=api_url,sql_record=param)
            return fn(*args,**kwargs)
        return logToSQL
    return warpper_fun
def log1(api_url=""):
    def warpper_fun(fn):
        def logToSQL(*args,**kwargs):
            account =  "未知"
            param = str(kwargs)
            add(name=account,content=api_url,sql_record=param)
            return fn(*args,**kwargs)
        return logToSQL
    return warpper_fun
if __name__ == "__main__":
    @log1(api_url="/api/1234")
    @log1(api_url="/api/888")
    def getIt(id=None,name=None,ip=None):
        print(1)
        return 1

    @log1(api_url="/api/9999")
    @log1(api_url="/api/888")
    def getIt1(id=None,name=None,ip=None):
        print(1)
        return 1

    getIt(id=5,name='333',ip='9999')
    getIt1(id=5,name='222',ip='8888')
    # getIt1()



